<template>


  <el-dialog
    top="20px"
    :title="defaultValue.title"
    :lock-scroll="tableConfig.lockScroll"
    :append-to-body="tableConfig.appendToBody"
    :visible="tableConfig.show"
    @close="tableConfig.show = false"
    :show-close="tableConfig.close"
    :destroy-on-close="tableConfig.destroyOnClose"
    width="1100px">

    <el-form size="small" ref="formOpsDeployRef" :rules="checkRule" :model="submitData" label-width="180px">

        <el-form-item label="场所" >
            <el-input disabled :value="site ? site.name : ''" />
        </el-form-item>
        <el-form-item label="计算机" >
            <el-input disabled :value="computerServerVo ? computerServerVo.name : ''" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-input disabled value="应用" />
        </el-form-item>

        <el-form-item label="环境" prop="envId">
          <el-select v-model="submitData.envId" placeholder="请选择环境" clearable @change="envChangeHandle">
            <el-option
              v-for="item in envOpt"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用" prop="appId">
          <el-select v-model="submitData.appId" placeholder="请选择应用" clearable @change="appChangeHandle">
            <el-option
              v-for="item in appOpt"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用分支" prop="appBranchId">
          <el-select v-model="submitData.appBranchId" placeholder="请选择应用分支" clearable>
            <el-option
              v-for="item in appBranchOpt"
              :key="item.id"
              :label="item.branchName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用tag" prop="tag">
          <el-input v-model="submitData.tag" />
        </el-form-item>



        <el-form-item label="部署基础位置" prop="basePath">
            <el-input v-model="submitData.basePath" type="textarea" :autosize="{minRows: 2}" />
        </el-form-item>
        <el-form-item label="备份目录" prop="bakPath">
          <el-input v-model="submitData.bakPath" type="textarea" :autosize="{minRows: 2}" />
        </el-form-item>


      <el-form-item label="启动和关闭方式" prop="startEnd">
            <mavon-editor v-model="submitData.startEnd" :toolbars="toolbars"
                        ref="startEndRef" @imgAdd="imgAddStartEnd" @imgDel="imgDel" />
        </el-form-item>
        <el-form-item label="部署过程" prop="deployProcess">
            <mavon-editor v-model="submitData.deployProcess" :toolbars="toolbars"
                        ref="deployProcessRef" @imgAdd="imgAddDeployProcess" @imgDel="imgDel" />
        </el-form-item>
        <el-form-item label="验证方式" prop="verification">
            <mavon-editor v-model="submitData.verification" :toolbars="toolbars"
                        ref="verificationRef" @imgAdd="imgAddVerification" @imgDel="imgDel" />
        </el-form-item>
        <el-form-item label="网络端口" prop="ports">
            <el-input placeholder="网络端口多个请使用英文逗号分隔" v-model="submitData.ports" />
        </el-form-item>
        <el-form-item label="部署人" prop="deployUser">
            <el-input v-model="submitData.deployUser" />
        </el-form-item>
        <el-form-item label="部署时间" prop="deployTime">
            <el-date-picker
              clearable
              v-model="submitData.deployTime"
              placement="bottom-start"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
        </el-form-item>




    </el-form>


    <span slot="footer" class="dialog-footer">
      <el-button plain type="warning" @click="toSaveUpd"
                 v-if="defaultValue.saveUpdSelect !== 'select'">{{ defaultValue.title }}
                 </el-button>
      <el-button plain type="primary" @click="tableConfig.show = false">关闭</el-button>
    </span>

  </el-dialog>


</template>

<script>

import http from '@/utils/http'
import {clearInvalid, getUploadImagePath} from "@/utils/utils"

export default {
  name: "OpsDeployAppSaveUpd",
  data() {
    return {
      // 表格的默认值
      tableConfig: {
        // 关闭时销毁 Dialog 中的元素
        destroyOnClose: true,
        // 弹出框是否打开
        show: false,
        // 是否显示关闭按钮
        close: true,
        // 下面2个属性解决打开弹出框后没有在最上面显示的问题，导致看到的内容是一半的，需要先将滚动条移到最上面
        lockScroll: false,
        appendToBody: true,
      },
      // 默认值，进入页面后的值
      defaultValue: {
        // 弹出框标题
        title: '查看',
        // 保存还是修改or查看,取值有 select | save | upd
        saveUpdSelect: 'select'
      },
      // 提交的数据
      submitData:{
        id: null,
        siteId: null,
        computerServerId: null,
        basePath: null,
        startEnd: null,
        deployProcess: null,
        verification: null,
        ports: null,
        deployUser: null,
        deployTime: null,
        bakPath: null,
        type: 1,
        tag: null,
        appBranchId: null,
        appId: null,
        componentVersionId: null,
        componentId: null,
        updateTime: null,
        updateId: null,
        createTime: null,
        createId: null,
        delType: null,
        envId: null,
      },
      // 校验规则
      checkRule: {
        // type: [{required: true, message: '请输入类型，工具、应用、组件', trigger: 'blur'}],
        envId: [{required: true, message: '请选择环境', trigger: 'change'}],
        appBranchId: [{required: true, message: '请选择应用分支', trigger: 'change'}],
        appId: [{required: true, message: '请选择应用', trigger: 'change'}],
      },
      // 场所
      site: null,
      // 当前计算机
      computerServerVo: {},
      // 工具类显示的东西 md 插件工具栏配置。下面的去掉一个就会少一个功能
      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: true, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true, // 预览
      },
      // 当前时间
      dateTime: {
        // 年月日 yyyy-MM-dd
        now: null,
        // 年部分 yyyy
        year: null,
        // 月部分 MM
        month: null,
      },
      // 环境信息
      envOpt: [],
      // 应用信息
      appOpt: [],
      // 应用分支
      appBranchOpt: [],
    }
  },
  methods: {
    /**
     * 初始化操作
     * @param operateType 操作类型,保存还是修改or查看,取值有 select \ save \ upd
     * @param obj 如果是修改和查看，则是详细数据,需要赋值
     * @param computerServerId 服务器id
     */
    async init(operateType, obj, computerServerId){
      this.defaultValue.saveUpdSelect = operateType
      this.clearOldData()
      this.getSiteById()
      this.getTime()
      await this.getEnvListPage()
      this.getComputerServerDetails(computerServerId)


      if (operateType === 'save'){
        this.defaultValue.title = '新增'

      } else if (operateType === 'upd'){
        this.defaultValue.title = '修改'
        // 要json处理下，否则会影响之前的值
        this.submitData = JSON.parse(JSON.stringify(obj.opsDeploy))
        this.submitData.envId = obj.envId
        this.envChangeHandle(obj.envId)
        this.appChangeHandle(obj.opsDeploy.appId)

      } else {
        // 可能查看
      }

      this.tableConfig.show = true
    },
    /**
     * 清理掉旧数据
     */
    clearOldData(){
      this.submitData = {
        id: null,
        siteId: null,
        computerServerId: null,
        basePath: null,
        startEnd: '',
        deployProcess: '',
        verification: '',
        ports: null,
        deployUser: null,
        deployTime: null,
        bakPath: null,
        type: "1",
        tag: null,
        appBranchId: null,
        appId: null,
        componentVersionId: null,
        componentId: null,
      }
    },
    /**
     * 是保存还是修改
     */
    toSaveUpd(){
      if (this.defaultValue.saveUpdSelect === 'save'){
        this.saveOpsDeploy()

      } else if (this.defaultValue.saveUpdSelect === 'upd'){
        this.updOpsDeploy()

      } else {

      }
    },
    /**
     * 保存
     */
    saveOpsDeploy(){
      this.submitData.type = "1"
      this.submitData.computerServerId = this.computerServerVo.id
      http.post("/opsDeploy/saveOpsDeploy", this.submitData).then(response => {
        let res = response.data;

        this.$message.success ("保存成功");
        this.$emit('getListPage', null)
        // 关闭弹出框,继续添加
        this.tableConfig.show = false

      }).catch(error => {
        this.$message.error (error.message);
      })
    },
    /**
     * 更新
     */
    updOpsDeploy(){
      clearInvalid(this.submitData)
      http.post("/opsDeploy/updOpsDeploy", this.submitData).then(response => {
        let res = response.data;

        this.$message.success ("更新成功");
        this.$emit('getListPage', null)
        // 关闭弹出框
        this.tableConfig.show = false

      }).catch(error => {
        this.$message.error (error.message);
      })
    },
    /**
     * 根据主键查询场所信息
     */
    getSiteById() {
      http.post("/opsSite/getSiteById", {
        siteId: this.$route.query.siteId,
      }).then(response => {
        let res = response.data;
        this.site = res.data

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * 计算机详情
     * @param computerServerId 服务器id
     */
    getComputerServerDetails(computerServerId) {
      http.post("/computer/getComputerServerDetails", {
        computerServerId: computerServerId
      }).then(response => {
        let res = response.data;
        this.computerServerVo = res.data

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * md的图片删除被触发
     * 这里的删除需要触发标签上面的删除才触发这个删除
     * @param pos 数组0 是文件序号1， 数组1 ，文件
     */
    imgDel(pos){
      // console.log(pos[0])
      // 图片是一个数组，那么这里直接通过pos[0]取出文件路径。
      http.post("/fileStorage/delImageByUrl", {
        url: pos[0],
      }).then(response => {
        let res = response.data;
        this.$message.success("删除图片成功");

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * md的图片新增被触发-启动和停止
     * @param pos 这里的pos就是图片的信息,示例 1 - 2 -3
     * @param file 上传的文件
     */
    imgAddStartEnd(pos, file){
      let formData = new FormData()
      formData.append("file", file)
      // 对应 com.sprouting.ops.interfaces.ConstantBase.FileSourceType
      formData.append("objectType", "12")
      formData.append("imageTypePath", "deploy/startEnd/" + this.dateTime.year + "/" + this.dateTime.month)

      http.postFileForm("/fileStorage/uploadImage", formData).then(response => {
        let res = response.data;
        // 替换在markerDown中的图片路径
        // this.$refs[ref].$img2Url(pos, getUploadImagePath(res.data.id));  动态替换
        this.$refs.startEndRef.$img2Url(pos, getUploadImagePath(res.data.id))
        this.$message.success("上传图片成功");

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * 获取当前时间
     */
    getTime() {
      http.get("/open/getTime", {}).then(response => {
        // yyyy-MM-dd HH:mm:ss
        let res = response.data;
        this.dateTime.now = res.data
        const date = new Date(this.dateTime.now)
        this.dateTime.year = date.getFullYear()
        // 月份从 0 开始，所以要 +1,提取月份（0-11 → 补零成 01-12）
        this.dateTime.month = (date.getMonth() + 1).toString().padStart(2, '0')

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * md的图片新增被触发-部署过程
     * @param pos 这里的pos就是图片的信息,示例 1 - 2 -3
     * @param file 上传的文件
     */
    imgAddDeployProcess(pos, file){
      let formData = new FormData()
      formData.append("file", file)
      // 对应 com.sprouting.ops.interfaces.ConstantBase.FileSourceType
      formData.append("objectType", "13")
      formData.append("imageTypePath", "deploy/process/" + this.dateTime.year + "/" + this.dateTime.month)

      http.postFileForm("/fileStorage/uploadImage", formData).then(response => {
        let res = response.data;
        // 替换在markerDown中的图片路径
        // this.$refs[ref].$img2Url(pos, getUploadImagePath(res.data.id));  动态替换
        this.$refs.deployProcessRef.$img2Url(pos, getUploadImagePath(res.data.id))
        this.$message.success("上传图片成功");

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * md的图片新增被触发-验证
     * @param pos 这里的pos就是图片的信息,示例 1 - 2 -3
     * @param file 上传的文件
     */
    imgAddVerification(pos, file){
      let formData = new FormData()
      formData.append("file", file)
      // 对应 com.sprouting.ops.interfaces.ConstantBase.FileSourceType
      formData.append("objectType", "14")
      formData.append("imageTypePath", "deploy/verification/" + this.dateTime.year + "/" + this.dateTime.month)

      http.postFileForm("/fileStorage/uploadImage", formData).then(response => {
        let res = response.data;
        // 替换在markerDown中的图片路径
        // this.$refs[ref].$img2Url(pos, getUploadImagePath(res.data.id));  动态替换
        this.$refs.verificationRef.$img2Url(pos, getUploadImagePath(res.data.id))
        this.$message.success("上传图片成功");

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * 环境信息查询
     */
    getEnvListPage() {
      return new Promise((resolve, reject) => {
        let query = {
          current: 1,
          size: 1000,
          siteId: this.$route.query.siteId,
        };
        http.post("/opsEnv/getListPage", query)
          .then(response => {
            this.envOpt = response.data.data.records;
            resolve(this.envOpt); // 返回 envOpt 数据
          })
          .catch(error => {
            this.$message.error(error.message);
            reject(error);
          });
      });
    },
    /**
     * 环境的值发生变化
     * @param value 目前的选中值
     */
    envChangeHandle(value){
      // 根据 id 找到完整 item,环境信息
      const item = this.envOpt.find(i => i.id === value) || null;
      if (!item) return;
      // 获取应用信息
      this.getAppByProductId(item)
    },
    /**
     * 根据产品id查询应用
     * @param env 环境信息
     */
    getAppByProductId(env){
      http.post("/opsApp/getAppByProductId", {
        productId: env.productId
      }).then(response => {
        let res = response.data;
        this.appOpt = res.data;

      }).catch(error => {
        this.$message.error (error.message);
      })
    },
    /**
     * 应用的值发生变化
     * @param value 应用id
     */
    appChangeHandle(value){
      let query = {
        current: 1,
        size: 999,
        appId: value
      }
      http.post("/opsAppBranch/getOpsAppBranchPageList", query).then(response => {
        let res = response.data;
        // 分页数据
        let data = res.data;
        // this.pageConfig.total = data.total;
        // this.pageConfig.current = data.current;
        // this.pageConfig.size = data.size;
        // 表格数据
        this.appBranchOpt = data.records

      }).catch(error => {
        this.$message.error(error.message);
      })
    },

  }
}
</script>

<style scoped>

</style>


